#include <iostream>
#include <string.h>
#include <pthread.h>
#include <unistd.h>


using namespace std;

int tickets = 10000;  //假设有一万张票

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;  //初始化锁

void *callfunc(void *args)
{
    const char* name = static_cast<const char*>(args);
    while (true)
    {
        pthread_mutex_lock(&mutex);  //加锁
        if(tickets > 0)
        {
            usleep(1000);
            cout << name << "抢到票了，tickets = " << tickets << endl;
            tickets--;
            pthread_mutex_unlock(&mutex);  //解锁
        }
        else
        {
            cout << name << "没有票了...." << endl;
            pthread_mutex_unlock(&mutex);  //这里也需要解锁
            break;
        }
        //sleep(1);
    }
}

int main()
{
    pthread_t tid1;
    pthread_t tid2;
    pthread_t tid3;
    pthread_t tid4;

    // int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void*), void *arg);
    pthread_create(&tid1, nullptr, callfunc, (void *)"thread 1");
    pthread_create(&tid2, nullptr, callfunc, (void *)"thread 2");
    pthread_create(&tid3, nullptr, callfunc, (void *)"thread 3");
    pthread_create(&tid4, nullptr, callfunc, (void *)"thread 4");

    // int pthread_join(pthread_t thread, void **value_ptr);
    int n = pthread_join(tid1, nullptr);
    cout << n << ":" << strerror(n) << endl;
    n = pthread_join(tid2, nullptr);
    cout << n << ":" << strerror(n) << endl;
    n = pthread_join(tid3, nullptr);
    cout << n << ":" << strerror(n) << endl;
    n = pthread_join(tid4, nullptr);
    cout << n << ":" << strerror(n) << endl;

    return 0;
}